<template>
	<view class="container">
		<view class="page-body">
			<view class='wrapper'>
				<view class='toolbar' style="height: auto;overflow-y: auto;">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold" @tap="format"></view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"  @tap="format"></view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline" @tap="format"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike" @tap="format"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center" @tap="format"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right" @tap="format"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify" @tap="format"></view>
					
					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
					
					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color" data-name="color" data-value="#0000ff" @tap="format"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''" class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00" @tap="format"></view>
					
					<view class="iconfont icon-date" @tap="insertDate"></view>
					
					<view class="iconfont icon--checklist" data-name="list" data-value="check" @tap="format"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list" data-value="ordered" @tap="format"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list" data-value="bullet" @tap="format"></view>
					
					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view>
					
					<view class="iconfont icon-outdent" data-name="indent" data-value="-1" @tap="format"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1" @tap="format"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header" :data-value="1" @tap="format"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao" data-name="script" data-value="sub" @tap="format"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao" data-name="script" data-value="super" @tap="format"></view>
					
					<view class="iconfont icon-shanchu" @tap="clear"></view>
					
					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl" data-name="direction" data-value="rtl" @tap="format"></view>
				</view>
				
				<view class="editor-wrapper">
					<editor id="editor" class="ql-container" :placeholder="placeholder" show-img-size show-img-toolbar
						show-img-resize @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
					</editor>
				</view>
			</view>
			<view>
				<button @click="submitDiary">发布日记</button>
			</view>
		</view>
	</view>
</template>



<script setup>
import { ref, onMounted } from 'vue'

// props 定义
const props = defineProps({
	placeholder: {
		type: String,
		default: '为这篇记录说点什么吧'
	}
})

// 响应式数据
const readOnly = ref(false)
const formats = ref({})
const editorCtx = ref(null)

// 编辑器准备完成
const onEditorReady = () => {
	// #ifdef APP-PLUS || MP-WEIXIN || H5
	uni.createSelectorQuery().select('#editor').context((res) => {
	editorCtx.value = res.context
	}).exec()
	// #endif

	// #ifdef MP-BAIDU
	editorCtx.value = requireDynamicLib('editorLib').createEditorContext('editor')
	// #endif
}


// 提交日记
const submitDiary = async () => {
    try {
        const content = await new Promise((resolve, reject) => {
            editorCtx.value.getContents({
                success: (res) => resolve(res.html),
                fail: reject
            });
        });
        uni.request({
            method: 'POST',
            url: 'http://localhost:9100/api/diary/save',
            data: content,
            header: {
                'bece_token': uni.getStorageSync('bece_token')
            },
            success: (res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    // 假设编辑器上下文有clear方法来清空内容，如下调用
                    editorCtx.value.clear({
                        success: () => console.log("clear success")
                    });
                    uni.showToast({
                        title: '发布日记成功',
                        duration: 2000
                    });
                    // 跳转页面，假设id是已定义好的变量
                    const id = 1; // 这里需要替换成真实有效的变量值
                    uni.navigateTo({
                        url: `/pages/home/home?id=${id}`
                    });
                } else {
                    uni.showToast({
                        title: res.data.msg,
                        duration: 2000
                    });
                }
            },
            fail: (err) => {
                console.error("请求失败:", err);
                uni.showToast({
                    title: '发布日记失败，请稍后再试',
                    duration: 2000
                });
            }
        });
    } catch (error) {
        console.error("获取编辑器内容失败:", error);
        uni.showToast({
            title: '获取日记内容出现问题，请稍后再试',
            duration: 2000
        });
    }
};
// 其他方法转换
const readOnlyChange = () => {
	readOnly.value = !readOnly.value
}

const undo = () => {
	editorCtx.value.undo()
}

const redo = () => {
	editorCtx.value.redo()
}

const format = (e) => {
	const { name, value } = e.target.dataset
	if (!name) return
	editorCtx.value.format(name, value)
}

const onStatusChange = (e) => {
	formats.value = e.detail
}

const insertDivider = () => {
	editorCtx.value.insertDivider({
		success: () => console.log('insert divider success')
	})
}

const clear = () => {
	uni.showModal({
		title: '清空编辑器',
		content: '确定清空编辑器全部内容？',
		success: res => {
			if (res.confirm) {
				editorCtx.value.clear({
					success: () => console.log("clear success")
				})
			}
		}
	})
}

const removeFormat = () => {
	editorCtx.value.removeFormat()
}

const insertDate = () => {
	const date = new Date()
		const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
		editorCtx.value.insertText({
			text: formatDate
		})
}

const insertImage = () => {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			editorCtx.value.insertImage({
				src: res.tempFilePaths[0],
				alt: '图像',
				success: () => console.log('insert image success')
			})
		}
	})
}

// 生命周期钩子
onMounted(() => {
	// #ifndef MP-BAIDU 
	uni.loadFontFace({
		family: 'Pacifico',
		source: 'url("https://sungd.github.io/Pacifico.ttf")'
	})
	// #endif
})
</script> 



<style>
@import "./editor-icon.css";

.page-body {
	height: auto;
}

.wrapper {
	height: 100%;
}

.editor-wrapper {
	height: 300px;
	background: #fff;
}

.iconfont {
	display: inline-block;
	padding: 8px 8px;
	width: 32px;
	height: 32px;
	cursor: pointer;
	font-size: 20px;
}

.toolbar {
	box-sizing: border-box;
	border-bottom: 0;
	font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	margin-bottom: 10px;
	background-color: #f2f2f2;
}

.ql-container {
	box-sizing: border-box;
	padding: 12px 15px;
	width: 100%;
	min-height: 30vh;
	height: 100%;
	font-size: 16px;
	line-height: 1.5;
}

.ql-active {
	color: #06c;
}

</style>

